﻿using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace NiuX.Objects;

public static class ByteExtensions
{
    /// <summary>
    /// 将对象转换为byte数组
    /// </summary>
    /// <param name="obj">被转换对象</param>
    /// <returns>转换后byte数组</returns>
    public static byte[] ToBytesWithBinaryFormatter(this object obj)
    {
        using var ms = new MemoryStream();
        IFormatter iFormatter = new BinaryFormatter();
        iFormatter.Serialize(ms, obj);
        return ms.GetBuffer();
    }

    /// <summary>
    /// 将byte数组转换成对象
    /// </summary>
    /// <param name="buff">被转换byte数组</param>
    /// <returns>转换完成后的对象</returns>
    public static object ToObjectWithBinaryFormatter(this byte[] buff)
    {
        using var ms = new MemoryStream(buff);
        IFormatter iFormatter = new BinaryFormatter();
        return iFormatter.Deserialize(ms);
    }

    /// <summary>
    /// 将byte数组转换成对象
    /// </summary>
    /// <param name="buff">被转换byte数组</param>
    /// <returns>转换完成后的对象</returns>
    public static T? ToObjectWithBinaryFormatter<T>(this byte[] buff) where T : class
    {
        return buff.ToObjectWithBinaryFormatter() as T;
    }
}